import { Upload } from "antd";
import { useState } from "react";
import axios from "axios";

const getOssConfig = async () => {
  const config = await axios.get("http://101.42.102.34:9000/getConfig");
  return config || {};
};

const AliyunOssUpload = (props) => {
  const { beforeUpload, children, ...restProps } = props;
  const [ossConfig, setOssConfig] = useState({});
  const customBeforeUpload = async (file, fileList) => {
    // 没有配置信息或者有效期已过，重新获取配置
    if (!ossConfig.expire || ossConfig.expire * 1000 < Date.now()) {
      const res = await getOssConfig();
      setOssConfig(res.data);
    }
    beforeUpload && beforeUpload(file, fileList);
    return true;
  };
  const getExtraData = (file) => {
    return {
      key: `${ossConfig.dir}${file.name}`, // 目录前缀和文件名拼接，没有目录前缀直接使用文件名即可
      policy: ossConfig.policy,
      OSSAccessKeyId: ossConfig.accessid,
      success_action_status: 200,
      signature: ossConfig.signature,
    };
  };
  return (
    <Upload
      {...restProps}
      beforeUpload={customBeforeUpload}
      action={ossConfig?.host}
      data={getExtraData}
    >
      {children}
    </Upload>
  );
};

export default AliyunOssUpload;
